Black Friday Sale Upgrade Your Home →

Create and Declare properties new Svelte 3 component

  • We start with the following code
HTML
<script>
let name = 'not'
let surname = 'hanii'
</script>
<style>
h1 {
color: royalblue;
}
</style>
<h1>My name is {name}</h1>
  • Let's create a new component that we're going to use to display our surname
  • Create a new file in your src/ directory, let's call it Surname.svelte
HTML
<script>
let surname = 'hanii'
</script>
<h1>My surname is {surname}</h1>
  • Of course this text is not visible because it isn't rendered in our app
  • Let's add it to our component by going back to App.svelte removing the surname declaration, and adding import Surname from 'Surname.svelte'
  • Notice that the h1 style tag in our App.svelte doesn't effect our surname component. If we want to style that component we can do it inside of Surname.svelte

6. Declare and pass in to a Svelte 3 component

  • Now our app displays a user info component that we're importing from UserInfo.svelte
HTML
<script>
let name = 'Not'
let surname = 'Hanii'
</script>
<style>
h1 {
color: royalblue;
}
</style>
<h1>My name is {name}</h1>
<h1>My surname is {surname}</h1>
  • And we're calling this from App.svelte
HTML
<script>
import UserInfo from './UserInfo.svelte'
</script>
<UserInfo />
  • Right now we don't have a way to change the values of UserInfo when we call it.
  • But we can pass them in as props and then add the export keyword in front of our variable declarations
  • In our UserInfo component we can set a default value for our prop by adding a definition export let name = "Hanii";

  Previous      Next